<template>
  <div class="user-container">
    <a-card class="card">
      <a-input
        v-model:value="searchValue"
        style="margin-bottom: 8px"
        placeholder="输入关键词过滤"
        @change="onChange"
      />
      <a-tree
        v-if="filterList?.length && filterList?.length > 0"
        :tree-data="filterList"
        :expandedKeys="expandedKeys"
        @expand="onExpand"
        :load="loading"
      >
      </a-tree>
      <a-empty v-else :image="false" description="无数据" />
    </a-card>
    <div class="user-right">
      <a-card class="card card-form">
        <a-form
          ref="formRef"
          :model="formState"
          name="horizontal_login"
          layout="inline"
          autocomplete="off"
          @finish="onFinish"
        >
          <a-form-item label="用户名" name="user">
            <a-input
              v-model:value="formState.user"
              placeholder="请输入用户名"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">查询</a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="() => formRef?.resetFields()">重置</a-button>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card class="card card-table">
        <a-table
          :dataSource="userData"
          :columns="columns"
          bordered
          :scroll="{ x: 900 }"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'role'">
              {{ ROLES[String(record.role) as keyof typeof ROLES].text }}
            </template>
            <template v-if="column.key === 'status'">
              <a-switch
                :checked="record.status"
                checked-children="启用"
                un-checked-children="禁用"
                @change="onChangeUserStatus(record)"
              />
            </template>
            <template v-if="column.key === 'action'">
              <div class="action-col">
                <a-button
                  type="primary"
                  size="small"
                  @click="onEditUser(record)"
                >
                  <template #icon>
                    <form-outlined />
                  </template>
                  编辑
                </a-button>
                <a-button
                  type="danger"
                  size="small"
                  v-if="!(record.role === 'super')"
                  @click="onDeleteUser"
                >
                  <template #icon>
                    <delete-outlined />
                  </template>
                  删除
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <FormModal
      :visible="formModalVisible"
      @update:visible="toggleFormVisible"
      :user-data="formUser || null"
    />
  </div>
</template>
<script lang="ts" setup name="User">
import SystemService from "@/service/systemService";
import { createVNode, onMounted, ref } from "vue";
import { FormInstance, Modal, TreeProps } from "ant-design-vue";
import { ITreeItem, IUser } from "@/type/System";
import cloneDeep from "lodash/cloneDeep";
import {
  ExclamationCircleOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import FormModal from "./components/formModal.vue";
import { ROLES } from "@/constants/role";

const columns = [
  {
    title: "用户名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "昵称",
    dataIndex: "nickName",
    key: "nickName",
  },
  {
    title: "性别",
    dataIndex: "sex",
    key: "sex",
  },
  {
    title: "关联角色",
    dataIndex: "role",
    key: "role",
  },
  {
    title: "手机号",
    dataIndex: "telephone",
    key: "telephone",
    width: 150,
  },
  {
    title: "用户状态",
    dataIndex: "status",
    key: "status",
  },
  {
    title: "用户描述",
    dataIndex: "message",
    key: "message",
  },
  {
    title: "创建时间",
    dataIndex: "creatTime",
    key: "creatTime",
  },
  {
    title: "操作",
    key: "action",
    width: 180,
    fixed: "right",
  },
];
const formRef = ref<FormInstance>();
const searchValue = ref("");
const treeList = ref<TreeProps["treeData"]>([]);
const filterList = ref<TreeProps["treeData"]>([]);
const expandedKeys = ref<string[]>(["1", "2", "3"]);
const loading = ref(false); // 树的load
const tableLoading = ref(false); // 表格的load
const formModalVisible = ref(false); // 表单展示弹框
const formUser = ref<IUser | null>(null); // 表单弹框的用户数据
const userData = ref<IUser[]>([]);
const formState = ref<{
  user: string;
}>({
  user: "",
});

const getSystemData = async () => {
  loading.value = true;
  const res = await SystemService.getApartment();
  treeList.value = res;
  filterList.value = res;
  loading.value = false;
};
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
};
const onChange = (values: InputEvent) => {
  let tempList = cloneDeep(treeList.value).filter((item: ITreeItem) => {
    if (item.title.includes(searchValue.value)) {
      return true;
    }
    item.children = item.children.filter((child: ITreeItem) => {
      if (child.title.includes(searchValue.value)) {
        return true;
      }
      return false;
    });
    return item.children.length > 0;
  });
  filterList.value = tempList;
  expandedKeys.value = tempList.map((item: ITreeItem) => {
    return item.key;
  });
};
const onFinish = () => {};
const getUserData = async () => {
  tableLoading.value = true;
  const res = await SystemService.getUsers();
  res.forEach((element: any) => {
    element.status = element.status === 1;
  });
  userData.value = res;
  tableLoading.value = false;
};
const onChangeUserStatus = (user: IUser) => {
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确定要更改 " + user.name + " 账户吗？",
    okText: "确定",
    cancelText: "取消",
    onOk() {
      user.status = !user.status;
    },
    onCancel() {},
  });
};
const onDeleteUser = () => {
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确定删除当前项吗？",
    okText: "确定",
    cancelText: "取消",
    onOk() {},
    onCancel() {},
  });
};
const toggleFormVisible = () => {
  formModalVisible.value = !formModalVisible.value;
};
const onEditUser = (user: IUser) => {
  formUser.value = user;
  toggleFormVisible();
};
onMounted(() => {
  getSystemData();
  getUserData();
});
</script>
<style lang="less" rel="stylesheet/less" scoped>
.user-container {
  margin: 6px;
  height: calc(100% - 50px);
  display: flex;

  .card {
    overflow: scroll;
    box-shadow: 0px 0px 12px rgb(0 0 0 / 12%);
    border-radius: 4px;
    margin: 8px 5px;
    min-width: 200px;
    overflow-x: scroll;
  }

  .user-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 700px;
    overflow-x: scroll;

    .card-form {
      height: auto;
    }

    .card-table {
      flex: 1;

      .action-col {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>
